﻿using System;
using System.Text;
using System.Net;
using System.IO;
using IAM.Interface.Common.Encrypt;
using IAM.Interface.Common.Abnormity;

namespace IAM.Interface.Common.Providers
{
    public class HttpProvider : IProvider
    {
        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="url">目的地址</param>
        /// <param name="xml">xml信息</param>
        public HttpProvider(string url, string xml)
        {
            _url = url;
            _xml = xml;
            _endecrypt = new EncryptDecrypt();//指定使用RijndaelManaged算法
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="digest">摘要</param>
        /// <param name="url">目的地址</param>
        /// <param name="xml">xml信息</param>
        public HttpProvider(string digest,string url, string xml)
        {
            _sign = digest;
            _url = url;
            _xml = xml;
            _endecrypt = new EncryptDecrypt();
        }
        #endregion
        #region 依据发出的请求返回响应的xml字符串
        public override string GetResponseStr()
        {
            string str = "";
            try
            {
                //获取请求xml
                SetWholeSendStr();
                byte[] bs = Encoding.ASCII.GetBytes(_sendstring);
                HttpWebRequest httpRequest = null;

                httpRequest = (HttpWebRequest)WebRequest.Create(_url);

                httpRequest.Method = "POST";

                //httpRequest.ContentType = "text/xml";
                httpRequest.ContentType = "application/x-www-form-urlencoded";
                httpRequest.ContentLength = bs.Length;

                using (Stream reqStream = httpRequest.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                    reqStream.Flush();
                }

                //httpRequest.UserAgent = @"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.40607; .NET CLR 1.1.4322)";
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();

                if (httpRequest.HaveResponse)
                {
                    StreamReader sr;

                    sr = new StreamReader(httpResponse.GetResponseStream(), Encoding.Default);
                    str = sr.ReadToEnd();

                    sr.Close();
                    httpResponse.Close();
                }
            }
            catch(Exception ex)
            {
                //ResponseException re = new ResponseException();
                //re.StatusCode = 414;
                throw (ex);
            }
            return str;
        }
        #endregion
    }
}
